import Taro from "@tarojs/taro";
// import QS from 'qs'
import {
  getStorage,
  clearStorage,
  getCurrentPageUrlWithArgs,
} from "..//utils/tools";
import { useUserStore } from "../store";
let needLoadingRequestCount = 0;
// loading配置，请求次数统计
function startLoading() {
  Taro.showLoading({ title: "加载中", mask: true });
}
function endLoading() {
  Taro.hideLoading();
} // 声明一个对象用于存储请求个数
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}
//loading是做了多个请求同时发起的时候防止动画叠加
// "https://nianchu.doupiaopiao.net";
// http://192.168.3.43:8001
//
export default function request(url, config: any = {}, needLoading = false) {
  const BASE_URL = "https://nianchu.doupiaopiao.net";
  // const BASE_URL = "http://192.168.110.71:8001";

  //默认加载都带动画设置false不加载
  const userStore = useUserStore();
  needLoading && showFullScreenLoading();
  return new Promise((resolve, reject) => {
    Taro.request({
      url: `${BASE_URL}${url}`,
      method: config.type.toUpperCase() || "GET",
      data: config.data || {},
      header: {
        "Content-type": "application/json",
        Authorization: userStore.Token,
        ...config.header,
      },
      success: (res) => {
        let { statusCode } = res;
        const success200 = () => {
          //-----------处理200成功 这里根据公司情况
          let { code, msg } = res.data;
          if (code === 1000) {
            resolve(res && res.data && res.data.data);
          }
          reject({ errMsg: msg });
        };
        const success401 = () => {
          //-----------------处理401 去登录
          let url = getCurrentPageUrlWithArgs();
          userStore.logout();
          Taro.redirectTo({
            url: `/pages/login/index?url=${encodeURIComponent(url)}`,
          });
        };
        const success500 = () => {
          reject({ errMsg: "服务器错误" });
        };
        const other = () => {
          reject({ errMsg: "未知错误" });
        };
        // ---------------------这里是扩展其他
        const actions = new Map([
          ["code_200", success200],
          ["code_401", success401],
          ["code_500", success500],
          ["default", other],
        ]);
        const events = (identity, status) => {
          const action: any =
            actions.get(`${identity}_${status}`) || actions.get("default");
          action.call(this);
        };
        events("code", statusCode);
      },
      fail: (error) => {
        error.errMsg = "请求失败";
        reject(error);
      },
      complete: (res) => {
        tryHideFullScreenLoading();
      },
    }).catch((error) => {
      error.errMsg = "网络错误";
      reject(error);
    });
  });
}
